/**
 * 弹珠控制逻辑
 */
class MarbleControl {
  constructor(physics) {
    this.physics = physics;
    this.selectedMarble = null;
    this.startPos = {x: 0, y: 0};
    this.endPos = {x: 0, y: 0};
  }

  // 选择弹珠
  selectMarble(marble) {
    this.selectedMarble = marble;
    this.startPos.x = marble.x;
    this.startPos.y = marble.y;
  }

  // 拖拽更新
  dragUpdate(x, y) {
    if (!this.selectedMarble) return;
    this.endPos.x = x;
    this.endPos.y = y;
  }

  // 释放弹珠
  release() {
    if (!this.selectedMarble) return;

    // 计算发射向量
    const dx = this.startPos.x - this.endPos.x;
    const dy = this.startPos.y - this.endPos.y;
    const power = Math.min(Math.sqrt(dx*dx + dy*dy) * 0.1, 15);

    // 应用力
    this.selectedMarble.vx = dx * power;
    this.selectedMarble.vy = dy * power;

    this.selectedMarble = null;
  }

  // 碰撞检测
  checkMarbleCollision(marble1, marble2) {
    const dx = marble1.x - marble2.x;
    const dy = marble1.y - marble2.y;
    const distance = Math.sqrt(dx*dx + dy*dy);
    
    if (distance < marble1.radius + marble2.radius) {
      // 简单弹性碰撞
      const angle = Math.atan2(dy, dx);
      const speed1 = Math.sqrt(marble1.vx*marble1.vx + marble1.vy*marble1.vy);
      const speed2 = Math.sqrt(marble2.vx*marble2.vx + marble2.vy*marble2.vy);
      
      marble1.vx = Math.cos(angle) * speed2;
      marble1.vy = Math.sin(angle) * speed2;
      marble2.vx = Math.cos(angle + Math.PI) * speed1;
      marble2.vy = Math.sin(angle + Math.PI) * speed1;
    }
  }
}

export default MarbleControl;
